test = {}

test.sleepers = {0x0001,0x0002}
--test.sleepers = {0x0181,0x0182,0x0180,0x0184}

test.caller = 0x0000
test.totle = 1000
test.count = 0
test.caller_delay = 5000

test.sleep_time = 20000
test.wakeup_time = 10000
test.caller_payload_len = 5
test.sleeper_payload_len = 20

test.caller_mark = 0x11

function receiveReport(rpkg)
	if(rpkg==nil)	then
		print("recv nothing")
		return
	end
	body = ""
	for i=1,#rpkg do			
		body = body..string.format("%02X ", rpkg[i])
	end
	print("收到了 %d data %04X->%d: %q",#rpkg,rpkg.addr, rpkg.port,body)
end

receive = receiveReport



function printNote()		
	print("这个程序用于多次休眠唤醒后，不能接收数据的异常情况")
	print("一个模块运行发送程序，每".. test.caller_delay/1000 .."秒发送一个包。")
	print("其他模块运行休眠程序，每次休眠".. test.sleep_time/1000 .."秒，然后唤醒".. test.wakeup_time/1000 .."秒")
	print("在唤醒时，如果收到数据包，就发送一个包回去。")
end

stop_caller = false

function runCaller()
	print("开始运行caller")
	stop_caller = false
	callerLoop()	
end
function stopCaller()
	print("停止caller")
	stop_caller = true
end



function callerLoop()
	for i=1,#test.sleepers do
		pkg={test.caller_mark}
		for i=2,test.caller_payload_len do
			pkg[i] = i
		end
		pkg.addr = test.sleepers[i]
		pkg.port = 48
		send__(pkg)
		print("caller发送了一个包到"..string.format("%04X",test.sleepers[i]))
	end
	if stop_caller then
		print("caller停止了")
		return
	end
	later(test.caller_delay,callerLoop)
end


stop_sleeper = false
function runSleeper()
	print("开始运行sleeper")
	receive = sleeperReceive
	stop_sleeper = false
	sleepersLoop1()
end
function stopSleeper()
	print("停止sleeper")
	stop_sleeper = true
end

function sleeperReceive(rpkg)
	if(rpkg==nil)	then
		print("recv nothing")
		return
	end
	if rpkg[1]==test.caller_mark then
		spkg={0x12}
		for i=2,test.sleeper_payload_len do
			spkg[i] = i
		end
		spkg.addr = rpkg.addr
		spkg.port = 48
		send__(spkg)
		print("sleeper收到了caller的包，回复了一个包。")
		return
	end
	if rpkg[1]==string.byte("h") and rpkg.port == 102 then
		print("收到握手"..rpkg[2])
		received_waik_up_sno = rpkg[2]
		return
	end
	receiveReport(rpkg)

end


function sleepersLoop1()
	pkg={string.byte("S")}
	pkg.addr = 0xfff0
	pkg.port = 111
	send__(pkg)
	print("睡眠。。。")
	later(test.sleep_time,sleepersLoop2)
end

function sleepersLoop2()
	print("唤醒！")
	waikUp()
	if stop_sleeper then
		print("sleeper停止了")
		return
	end
	later(test.sleep_time,sleepersLoop1)
end
waik_up_sno = 1	
received_waik_up_sno = 0 
function waikUp()	
	if received_waik_up_sno == waik_up_sno then
		print("唤醒成功！")
		received_waik_up_sno = -1
		return
	end
	if(waik_up_sno<200) then
		waik_up_sno = waik_up_sno+1
	else
		waik_up_sno = 1
	end
	pkg={string.byte("H"),waik_up_sno}
	pkg.addr = 0xfff0
	pkg.port = 102
	send__(pkg)
	print("唤醒握手包"..waik_up_sno)
	later(100,waikUp)
end





function __receive(rpkg)
	receive(rpkg)
	return 
end




printNote()	